﻿using System;
using System.Collections;

namespace Data_Storages
{
    public sealed class NetClient : IDataStorage
    {
        private NetClientConnection _connection;
        public event EventHandler<NetClientMessageEventArgs> MessageEvent;

        public bool Connected { get; private set; }

        public NetClient()
        {
            Connected = false;
            _connection = new NetClientConnection();
        }

        ~NetClient()
        {
            if (Logout())
            {
                _connection = null;
                Connected = false;
            }
        }

        private bool AddHost(string hostName, int port)
        {
            return _connection.AddHost(hostName, port) > 0;
        }

        public bool Login(string hostName, int port)
        {
            if (AddHost(hostName, port))
            {
                Connected = _connection.Connect();
            }
            return _connection.Connected;
        }

        public bool Send(byte[] message)
        {
            return _connection.Connected && _connection.Send(message);
        }

        public byte[] Receive()
        {
            if (!_connection.Connected)
            {
                throw new Exception("Error while receiving");
            }
            var message = _connection.Recieve();
            OnMessageEvent(new NetClientMessageEventArgs(message));
            return message;
        }

        public bool Logout()
        {
            if (_connection.Connected)
            {
                _connection.Disconnect();
            }
            Connected = _connection.Connected;
            return _connection.Connected;
        }

        private void OnMessageEvent(NetClientMessageEventArgs args)
        {
            var handler = MessageEvent;
            if (handler != null)
            {
                handler(this, args);
            }
        }

        public void Save(ArrayList data)
        {
            throw new NotImplementedException();
        }

        public ArrayList Load()
        {
            throw new NotImplementedException();
        }
    }
}
